from LinkPoint import LinkPoint
from Polyline import Polyline


class LinkSegs_dlook:
    def __init__(self, segs):
        self.segs = segs
        self.contours = []
        self.polys = []
        self.dic = {}
        self.link()

    def createLpDic(self):
        dic = {}
        for seg in self.segs:
            lp1, lp2 = LinkPoint(seg.A), LinkPoint(seg.B)
            lp1.other, lp2.other = lp2, lp1
            l1 = (lp1.x, lp1.y)
            l2 = (lp2.x, lp2.y)
            if l1 not in dic.keys():
                dic[l1] = []
            dic[l1].append(lp1)
            if l2 not in dic.keys():
                dic[l2] = []
            dic[l2].append(lp2)
        self.dic = dic
        return dic

    def findUnusedPnt(self, dic=None):
        if dic is None:
            dic = self.dic
        for pnts in dic.values():
            for pnt in pnts:
                if not pnt.used:
                    return pnt
        return None

    def findNextPnt(self, p, dic=None):
        if dic is None:
            dic = self.dic
        other = p.other
        pnts = dic[(other.x, other.y)]
        for pnt in pnts:
            if pnt is not other:
                return pnt
        return None

    def link(self):
        self.createLpDic()
        while True:
            p = self.findUnusedPnt()
            if p is None:
                break
            poly = Polyline()
            while True:
                poly.addPoint(p.toPoint3D())
                p.used, p.other.used = True, True
                p = self.findNextPnt(p)
                if poly.isClosed():
                    self.contours.append(poly)
                    break
                if p is None:
                    self.polys.append(poly)
                    break
